﻿using UnityEngine;
using SevenZip;
using System.IO;
using System;

namespace LzmaHelper {
    public struct LzmaParams {
        public string inputPath;
        public string outputPath;
        public long outputSize;
        public string error;
        public ILzmaProgress progress;
    }

    public interface ILzmaProgress : ICodeProgress {

    }

    public class LzmaCoder {
        public static void Compress (ref LzmaParams myParams)
        {
            SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder();
            FileStream inputFS = new FileStream(myParams.inputPath, FileMode.Open);
            FileStream outputFS = new FileStream(myParams.outputPath, FileMode.Create);
            try
            {
                encoder.WriteCoderProperties(outputFS);
                encoder.Code(inputFS, outputFS, inputFS.Length, -1, myParams.progress);
            } catch (Exception e)
            {
                myParams.error = e.Message;
                Debug.LogError(e.Message);
            } finally
            {
                outputFS.Flush();
                outputFS.Close();
                inputFS.Close();
            }
        }

        public static void Decompress (ref LzmaParams myParams)
        {
            SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder();
            FileStream inputFS = new FileStream(myParams.inputPath, FileMode.Open);
            FileStream outputFS = new FileStream(myParams.outputPath, FileMode.Create);
            try
            {
                const int propertiesSize = 5;
                byte[] properties = new byte[propertiesSize];
                inputFS.Read(properties, 0, properties.Length);
                decoder.SetDecoderProperties(properties);
                decoder.Code(inputFS, outputFS, inputFS.Length, myParams.outputSize, myParams.progress);
            } catch (Exception e)
            {
                myParams.error = e.Message;
                Debug.LogError(e.Message);
            } finally
            {
                outputFS.Flush();
                outputFS.Close();
                inputFS.Close();
            }
        }
    }
}
